//
//  TL_FacebookManager.m
//  WXReader
//
//  Created by LL on 2020/9/8.
//  Copyright © 2020 Andrew. All rights reserved.
//

#import "TL_FacebookManager.h"

#import <FBSDKLoginKit/FBSDKLoginKit.h>

@interface TL_FacebookManager ()

@property (nonatomic, assign) TL_FacebookState state;

@end

@implementation TL_FacebookManager

SINGLETON_IMPLEMENTATION(TL_FacebookManager)

- (void)tunedUpFacebookWithState:(TL_FacebookState)state {
    _state = state;
    
    MK_WEAK_SELF
    
    FBSDKLoginManager *loginManager = [FBSDKLoginManager new];
    FBSDKLoginConfiguration *configuration =
      [[FBSDKLoginConfiguration alloc] initWithPermissions:@[@"public_profile", @"email"]
                                                  tracking:FBSDKLoginTrackingLimited
                                                     nonce:@"12321"];
    
    [loginManager logInFromViewController:[TL_ViewHelper getCurrentViewController] configuration:configuration completion:^(FBSDKLoginManagerLoginResult * _Nullable result, NSError * _Nullable error) {
        if (error) {
            [weakSelf facebookFail:state == TL_FacebookStateLogin ? WXLocalizedString(@"登录失败") : WXLocalizedString(@"绑定失败")];
        } else if (result.isCancelled) {
            [weakSelf facebookFail:WXLocalizedString(@"取消")];
        } else {
            // 登录成功
            [self fetchUserProfile];
        }
    }];
}
- (void)fetchUserProfile {
    NSLog(@"currentAccessToken:%@",[FBSDKAccessToken currentAccessToken]);
    
//    if (![FBSDKAccessToken currentAccessToken]) {
//        return;
//    }
    
    FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
                                  initWithGraphPath:@"me"
                                  parameters:@{@"fields": @"id, name, email, picture.type(large)"}];
    
    
    [request startWithCompletion:^(id<FBSDKGraphRequestConnecting>  _Nullable connection, id  _Nullable result, NSError * _Nullable error) {
        
        if (!error) {
            NSLog(@"用户信息: %@", result);
            
            NSString *userID = result[@"id"];
            NSString *userName = result[@"name"];
            NSString *userEmail = result[@"email"];
            NSString *pictureURL = result[@"picture"][@"data"][@"url"];
            
            NSLog(@"用户ID: %@", userID);
            NSLog(@"用户名: %@", userName);
            NSLog(@"邮箱: %@", userEmail);
            NSLog(@"头像URL: %@", pictureURL);
            
            // 在这里处理用户信息，比如发送到你的服务器
            [self thirdPartyLogin:@"1" andUserId:@"" andUserDict:@{
                @"id":userID,
                @"avatar":pictureURL,
                @"name":userName,
            }];
            
        } else {
            NSLog(@"获取用户信息失败: %@", error.localizedDescription);
        }
    }];
}
/// 第三方登录
- (void)thirdPartyLogin:(NSString *)token andUserId:(NSString *)userID andUserDict:(NSDictionary *)dict{
    if (kObjectIsEmpty(token)) {
        [self facebookFail:_state == TL_FacebookStateLogin ? WXLocalizedString(@"登录失败") : WXLocalizedString(@"绑定失败")];
    } else {
        MK_WEAK_SELF
        NSString *alertTitle = _state == TL_FacebookStateLogin ? WXLocalizedString(@"正在登录") : WXLocalizedString(@"正在绑定");
        MBProgressHUD *loginHUD = [kMainWindow showDarkHUDFromText:alertTitle];
        
        //        [TL_AnalyticsManager logEvent:@"login" params:@{@"plateform":@"1"}];
        //@{@"accessToken":token,@"fbUserId":userID}
        
        NSDictionary *param = dict;
        
        [APIManager sendPostRequest:_state == TL_FacebookStateLogin ? [APIURLManager Facebook_User_Login] : [APIURLManager Facebook_Bind_params] parameters:param model:TL_UserInfoModel.class success:^(BOOL success, TL_UserInfoModel *  _Nullable responseData, APIResponse * _Nonnull requestModel) {
            
            [loginHUD hideAnimated:YES];
            if (success) {
                if (_state == TL_FacebookStateLogin) {
                    TL_UserInfoModel *usermodel = [TL_UserInfoModel mj_objectWithKeyValues:requestModel.data[@"userInfo"]];
                    NSString *token = requestModel.data[@"token"];
                    [[NSUserDefaults standardUserDefaults] setObject:token forKey:@"userToken"];
                    NSDictionary *userDataDict = [usermodel mj_keyValues];
                    [[NSUserDefaults standardUserDefaults] setObject:userDataDict forKey:@"UserInfoModelDict"];
                }
                if ([weakSelf.delegate respondsToSelector:@selector(facebookLoginSuccess:userInfo:)]) {
                    [weakSelf.delegate facebookLoginSuccess:weakSelf userInfo:TL_UserInfoModel.shareInstance];
                }
            } else {
                [self facebookFail:requestModel.message ?: (self.state == TL_FacebookStateLogin ? WXLocalizedString(@"登录失败") : WXLocalizedString(@"绑定失败"))];
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [loginHUD hideAnimated:YES];
            [self facebookFail:self.state == TL_FacebookStateLogin ? WXLocalizedString(@"登录失败") : WXLocalizedString(@"绑定失败")];
        }];
        loginHUD.closeBlock = ^{
            [self facebookFail:self.state == TL_FacebookStateLogin ? WXLocalizedString(@"登录失败") : WXLocalizedString(@"绑定失败")];
        };
    }
}

- (void)facebookFail:(NSString *)error {
    if ([self.delegate respondsToSelector:@selector(facebookLoginFail:error:)]) {
        [self.delegate facebookLoginFail:self error:error];
    }
}

@end
